package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MediaGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        // 断送用户是否在进行登录,如果是,直接允许
        if (path.contains("login")) {
            return chain.filter(exchange);
        }
        // 判断用户是否携带token,如果没有,直接返回未授权
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 鉴权不通过,返回状态码没有权限
            return response.setComplete(); // 结束访问
        }
        // 有token,解析token判断是否有效或者是否过期
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claimsBody);
        if (result > 0) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 鉴权不通过,返回状态码没有权限
            return response.setComplete(); // 结束访问
        }
        // 将用户信息设置到请求头,以便被之后访问的微服务获取
        assert claimsBody != null;
        Object userId = claimsBody.get("userId");
        String newPath = request.getURI().getPath();
        ServerHttpRequest newRequest = request
                    .mutate()
                    .headers(httpHeaders -> httpHeaders.add("userId",userId.toString()))
                    .path(newPath)
                    .build();
        if (result == 0) {
            // token有效,允许,但有效期不足,为用户续约
            // 由于token在存放在用户端,如果由用户服务提供续约接口,gateway通过feign调用,还要返回给用户,麻烦
            // 不如把token存放在redis,用户携带的token用于鉴权
            return chain.filter(exchange.mutate().request(newRequest).response(response).build());
        } else {
            return chain.filter(exchange);// 鉴权通过且有效期充足,直接放行
        }
    }

    // 这是过滤器的优先级排序,过滤器的优先级:局部过滤器>默认过滤器>自定义全局过滤器
    @Override
    public int getOrder() {
        return 0;
    }
}
